<template>
  <view class="test-page">
    <view class="test-header">
      <text class="test-title">API 接入测试</text>
    </view>

    <view class="test-section">
      <text class="section-title">认证测试</text>
      <button class="test-btn" @click="testLogin">测试登录</button>
      <button class="test-btn" @click="testLoginError">测试错误登录</button>
      <button class="test-btn" @click="testRegister">测试注册</button>
      <button class="test-btn" @click="testLogout">测试登出</button>
    </view>

    <view class="test-section">
      <text class="section-title">用户管理测试</text>
      <button class="test-btn" @click="testGetUser">获取用户信息</button>
      <button class="test-btn" @click="testUpdateUser">更新用户信息</button>
      <button class="test-btn" @click="testUploadAvatar">测试头像上传</button>
    </view>

    <view class="test-section">
      <text class="section-title">大棚管理测试</text>
      <button class="test-btn" @click="testGetGreenhouses">获取大棚列表</button>
      <button class="test-btn" @click="testCreateGreenhouse">创建大棚</button>
    </view>

    <view class="test-section">
      <text class="section-title">作物管理测试</text>
      <button class="test-btn" @click="testGetCrops">获取作物选项</button>
    </view>

    <view class="test-results">
      <text class="results-title">测试结果：</text>
      <scroll-view class="results-content" scroll-y>
        <text class="result-item" v-for="(result, index) in testResults" :key="index">
          {{ result }}
        </text>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { authApi, userApi, greenhouseApi, cropApi } from '../../api/index.js'
import { setToken, getToken } from '../../utils/auth.js'

const testResults = ref([])

const addResult = (message) => {
  const timestamp = new Date().toLocaleTimeString()
  testResults.value.unshift(`[${timestamp}] ${message}`)
}

const testLogin = async () => {
  try {
    addResult('开始测试登录...')
    const response = await authApi.login('testuser', '123456')
    addResult(`登录成功: ${JSON.stringify(response)}`)

    if (response.data && response.data.token) {
      setToken(response.data.token)
      addResult('Token 已保存')
    }
  } catch (error) {
    addResult(`登录失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testLoginError = async () => {
  try {
    addResult('开始测试错误登录（用户名或密码错误）...')
    const response = await authApi.login('wronguser', 'wrongpassword')
    addResult(`意外成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`预期的登录失败: ${error.message || JSON.stringify(error)}`)
    addResult(`错误对象结构: code=${error.code}, message=${error.message}`)

    // 验证是否正确处理了401错误
    if (error.code === 401) {
      addResult('✅ 401错误处理正确，没有自动跳转登录页')
    } else {
      addResult('❌ 错误处理可能有问题')
    }
  }
}

const testRegister = async () => {
  try {
    addResult('开始测试注册...')
    const username = 'testuser' + Date.now()
    const response = await authApi.register(username, '123456')
    addResult(`注册成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`注册失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testLogout = async () => {
  try {
    addResult('开始测试登出...')
    const response = await authApi.logout()
    addResult(`登出成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`登出失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testGetUser = async () => {
  try {
    addResult('开始获取用户信息...')
    const response = await userApi.getCurrentUser()
    addResult(`获取用户信息成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`获取用户信息失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testUpdateUser = async () => {
  try {
    addResult('开始更新用户信息...')
    const response = await userApi.updateCurrentUser({
      nickname: '测试用户',
      email: 'test@example.com'
    })
    addResult(`更新用户信息成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`更新用户信息失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testUploadAvatar = () => {
  addResult('开始测试头像上传...')



  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      try {
        addResult(`选择图片成功: ${res.tempFilePaths[0]}`)
        addResult('开始上传头像...')

        const response = await userApi.uploadAvatar(res.tempFilePaths[0])
        addResult(`头像上传成功: ${JSON.stringify(response)}`)
      } catch (error) {
        addResult(`头像上传失败: ${error.message || JSON.stringify(error)}`)
      }
    },
    fail: (error) => {
      addResult(`选择图片失败: ${error.errMsg || JSON.stringify(error)}`)
    }
  })
}

const testGetGreenhouses = async () => {
  try {
    addResult('开始获取大棚列表...')
    const response = await greenhouseApi.getGreenhouseList()
    addResult(`获取大棚列表成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`获取大棚列表失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testCreateGreenhouse = async () => {
  try {
    addResult('开始创建大棚...')
    const response = await greenhouseApi.createGreenhouse({
      name: '测试大棚' + Date.now(),
      crop: '番茄',
      area: 100,
      type: 'glass',
      remark: '这是一个测试大棚'
    })
    addResult(`创建大棚成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`创建大棚失败: ${error.message || JSON.stringify(error)}`)
  }
}

const testGetCrops = async () => {
  try {
    addResult('开始获取作物选项...')
    const response = await cropApi.getCropOptions()
    addResult(`获取作物选项成功: ${JSON.stringify(response)}`)
  } catch (error) {
    addResult(`获取作物选项失败: ${error.message || JSON.stringify(error)}`)
  }
}
</script>

<style scoped>
.test-page {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.test-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.test-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.test-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.test-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 30rpx;
  margin: 10rpx;
  font-size: 24rpx;
}

.test-results {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  height: 400rpx;
}

.results-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.results-content {
  height: 300rpx;
}

.result-item {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 10rpx;
  padding: 10rpx;
  background-color: #f9f9f9;
  border-radius: 4rpx;
}
</style>
